<template>
  <view class="content">
    <roc-navbar title="个人信息"></roc-navbar>
    <view class="u-p-20">
      <u-form ref="formRef" :model="form" :rules="rules">
        <u-form-item label="头像" prop="avatar">
          <roc-upload-image
            :action="uploadApi"
            :header="{ token: getToken() }"
            v-model="form.avatar"
            :file-list="form.avatar"
          ></roc-upload-image>
        </u-form-item>
        <u-form-item label="名称" prop="name">
          <u-input placeholder="请输入用户名称" v-model="form.name"></u-input>
        </u-form-item>
        <u-form-item><u-button type="primary" @click="submit">修改</u-button></u-form-item>
      </u-form>
    </view>
  </view>
</template>

<script>
import { mapState } from 'vuex'
import { cloneDeep } from 'lodash-es'
import { updateUserProfile } from '@/mock/user.js'

export default {
  data() {
    return {
      form: {
        avatar: [],
        name: '',
      },
      rules: {
        name: [{ required: true, message: '名称不能为空', trigger: ['change', 'blur'] }],
      },
    }
  },
  onLoad() {
    this.displayFormData()
  },
  onReady() {
    this.$refs['formRef'].setRules(this.rules)
  },
  methods: {
    /**
     * 回显form数据
     */
    displayFormData() {
      this.form.avatar = [this.$store.state.user.avatar]
      this.form.name = this.$store.state.user.name
    },
    /**
     * 修改用户信息提交
     */
    submit() {
      this.$refs['formRef']
        .validate()
        .then(() => {
          const _form = cloneDeep(this.form)
          _form.avatar = _form.avatar.join(',')
          updateUserProfile(_form).then(() => {
            this.$u.toast('修改成功')
          })
        })
        .catch(errors => {
          console.error('表单校验失败', errors)
        })
    },
  },
}
</script>

<style lang="scss" scoped></style>
